//
//  UIImage+imagedown.m
//  美女我们旅游吧
//
//  Created by lanou3g on 14-12-7.
//  Copyright (c) 2014年 wy. All rights reserved.
//

#import "UIImage+imagedown.h"

@implementation UIImage (imagedown)
+(UIImage *)imageDownWithurlstring:(NSString *)urlstring
                       imagebolock:(mybolock)ib
{
    NSString *fileName = [[urlstring componentsSeparatedByString:@"/"] lastObject];
    
    NSString *documents=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    NSString *filePath = [documents stringByAppendingPathComponent:fileName];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
        {
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
        if (image)
            {
            return image;
        }
    }

    //使用传进来的url字符串转成nsurl
    NSURL *url=[NSURL URLWithString:urlstring];
    
    
    NSURLRequest *requset=[NSURLRequest requestWithURL:url];
    
    
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *respose,NSData *data,NSError *error)
     {
     
     if (![data writeToFile:filePath atomically:YES]) 
        {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
     }
         //解析图片,使用解析好的data转化成uiimage
         UIImage *image=[UIImage imageWithData:data];
         //第二次赋值时调用block并将解析好的image作为参数传入
     if (image)
         {
         ib(image);
     }
     else
         {
         ib([UIImage imageNamed:@"default_userhead.jpg"]);
         }
         
     }];
    //因为异步请求线程慢,所以提前返回一个占位图片
    return [UIImage imageNamed:@"default_userhead.jpg"];
   
}

@end
